export default class DeviceCamera{
  mediaStream = null
  active = false
  constructor(width, height){
    this.width = width || 200
    this.height = height || 200
  }

  async startCamera(videoDom, cameraFront=true) {
    const width = this.width;
    const height = this.height;
    const constraints = {
      //参数
      video: {
        // width,
        // height,
        // facingMode: { exact: "environment" }, // 后置
        facingMode: cameraFront ? 'user' : { exact: "environment" },
      },
      audio: false,
    };
    //获得video摄像头区域
    // videoDom.width = width;
    // videoDom.height = height;
    //返回的Promise对象
    try {
      this.mediaStream = await navigator.mediaDevices.getUserMedia(constraints);
    } catch (e) {
      alert('打开摄像头失败，需要授予摄像头权限哦')
      return
    }
    videoDom.srcObject = this.mediaStream;
    videoDom.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
    videoDom.play();
    this.active = true
  }

  stopCamera(){
    this.mediaStream.getVideoTracks().forEach(element => {
      element.stop()
    });
    this.active = false
  }
}